package com.tongzhan.service.impl;

import com.tongzhan.base.PageInfo;
import com.tongzhan.base.Return;
import com.tongzhan.data.vo.InformDetailsVO;
import com.tongzhan.data.vo.InformVO;
import com.tongzhan.data.vo.PicVO;
import com.tongzhan.entity.User;
import com.tongzhan.entity.religion.Inform;
import com.tongzhan.entity.religion.ModuleSign;
import com.tongzhan.file.FileGenerate;
import com.tongzhan.repository.UserRepository;
import com.tongzhan.repository.religion.InformRepository;
import com.tongzhan.repository.religion.ModuleSignRepository;
import com.tongzhan.service.InformService;
import com.tongzhan.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class InformServiceImpl implements InformService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private InformRepository informRepository;

    @Autowired
    private ModuleSignRepository signRepository;

    @Override
    public Return newInform(Integer type, Inform inform) {
        if (type == 0) {
            //接收者权限编码列表
            List<String> codes = new ArrayList<>(Arrays.asList(inform.getRecipientType().split(",")));
            //通知角标提醒
            List<ModuleSign> signList = signRepository.findAll(new Query().addCriteria(Criteria.where("DutiesCode").in(codes)));
            if (!CollectionUtils.isEmpty(signList)) {
                for (ModuleSign sign : signList) {
                    //通知类型角标加一
                    sign.setNotify(sign.getNotify() + 1);
                    signRepository.updateByPrimaryKey(sign);
                }
            }
            //记录未读条数
//            int unReadCount = 0;
//            for (String dutiesCode : split) {
//                //对应类型的用户列表
//                List<User> userList
//                        = userRepository.findAll(new Query().addCriteria(Criteria.where("DutiesCode").is(dutiesCode)));
//                if (!CollectionUtils.isEmpty(userList)) {
//                    for (User receiveUser : userList) {
//                        InformReceive receive = new InformReceive();
//                        receive.setInformCode(inform.getInformCode());
//                        receive.setInitiatorType(inform.getInitiatorType());
//                        receive.setTitle(inform.getTitle());
//                        receive.setUserName(user.getUserName());
//                        receive.setRealName(user.getRealName());
//                        receive.setDuties(user.getDuties());
//                        receive.setDutiesCode(user.getDutiesCode());
//                        receive.setStreetCode(user.getStreetCode());
//                        receive.setStreetName(user.getStreetName());
//                        receive.setReligionCode(user.getReligionCode());
//                        receive.setReligionName(user.getReligionName());
//                        receive.setSiteCode(user.getSiteCode());
//                        receive.setSiteName(user.getSiteName());
//                        receive.setSiteDutiesCode(user.getSiteDutiesCode());
//                        receive.setSiteDutiesName(user.getSiteDutiesName());
//                        receive.setState("未接收");
//                        receive.setTime(LocalDateTime.now());
//                        informReceiveRepository.insert(receive);
//                        unReadCount++;
//                    }
//                }
//            }
//            inform.setUnread(String.valueOf(unReadCount));
            inform.setType("Inform");
        } else {
            //法规角标提醒：镇街道、村社区、宗教团体、宗教场所、民间信仰点
            List<String> codes = Arrays.asList("02", "03", "04", "05", "07");
            List<ModuleSign> signList = signRepository.findAll(new Query().addCriteria(Criteria.where("DutiesCode").in(codes)));
            if (!CollectionUtils.isEmpty(signList)) {
                for (ModuleSign sign : signList) {
                    //法规类型角标加一
                    sign.setLaw(sign.getLaw() + 1);
                    signRepository.updateByPrimaryKey(sign);
                }
            }
            inform.setType("Law");
        }
        inform.setIsDeleted(0);
        inform.setTime(LocalDateTime.now());
        //生成图片和附件信息
        FileGenerate.generate(inform.getPicture(), inform.getUserName());
        FileGenerate.generate(inform.getAttachment(), inform.getUserName());
        //插入通知数据
        informRepository.insert(inform);
        return new Return(Return.SUCCESS, "操作成功");
    }

    @Override
    public Return getInformList(String userId, Integer type, Integer page, Integer size) {
        //用户信息
        User user = userRepository.findByPrimaryKey(userId);
        if (user == null) {
            return new Return(Return.FAIL, "用户不存在");
        }
        //查询条件
        Query query = new Query();
        if (type == 0) {
            query.with(Sort.by(Sort.Direction.DESC, "DutiesCode", "Time"));
            //通知
            query.addCriteria(Criteria.where("IsDeleted").is(0).and("Type").is("Inform"));
            //权限编码
            String dutiesCode = user.getDutiesCode();
            if (dutiesCode.equals(ThreadLocalUtil.STREET_CODE)) {
                //统战部镇街道
                dutiesCode = "02";
            }
            if (dutiesCode.equals(ThreadLocalUtil.VILLAGE_CODE)) {
                //统战部村社区
                dutiesCode = "05";
            }
            //需要过滤的通知的用户
            List<String> codes = Arrays.asList("02", "03", "04", "05", "07");
            if (codes.contains(dutiesCode)) {
                //其他用户显示自己的列表
                query.addCriteria(Criteria.where("RecipientType").regex(".*?" + dutiesCode + ".*"));
            }
            //通知类型角标重置
            ModuleSign sign = signRepository.findByPrimaryKey(userId);
            if (sign != null) {
                sign.setNotify(0L);
                signRepository.updateByPrimaryKey(sign);
            }
        } else {
            query.with(Sort.by(Sort.Direction.DESC,  "Time"));
            //法规
            query.addCriteria(Criteria.where("IsDeleted").is(0).and("Type").is("Law"));
            //法规类型角标重置
            ModuleSign sign = signRepository.findByPrimaryKey(userId);
            if (sign != null) {
                sign.setLaw(0L);
                signRepository.updateByPrimaryKey(sign);
            }
        }
        //通知列表
        Page<Inform> informPage = informRepository.findPage(query, PageRequest.of(page - 1, size));
        //VO
        List<InformVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(informPage.getContent())) {
            for (Inform inform : informPage.getContent()) {
                InformVO vo = new InformVO();
                vo.setInformCode(inform.getInformCode());
                vo.setUserName(inform.getUserName());
                vo.setRealName(inform.getRealName());
                vo.setTitle(inform.getTitle());
                vo.setTime(inform.getTime());
                vos.add(vo);
            }
        }
        //分页信息
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPage(page);
        pageInfo.setSize(vos.size());
        pageInfo.setTotal(informPage.getTotalElements());
        //封装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("informList", vos);
        map.put("pageInfo", pageInfo);
        return new Return(map);
    }

    @Override
    public Return informDetails(String userId, String informCode) {
        //通知信息
        Inform inform = informRepository.findByPrimaryKey(informCode);
        //用户信息
        User user = userRepository.findByPrimaryKey(userId);
        if (user == null) {
            return new Return(Return.FAIL, "用户不存在");
        }
        //VO
        InformDetailsVO vo = new InformDetailsVO();
//        if ("Inform".equals(inform.getType()) && !"00".equals(user.getDutiesCode())
//                && !"01".equals(user.getDutiesCode())) {
//            //查询接收的用户通知，修改状态
//            InformReceive receive = informReceiveRepository.findOne(new Query().addCriteria(Criteria.where("DutiesCode").is(user.getDutiesCode())
//                    .and("InformCode").is(informCode)
//                    .and("UserName").is(user.getUserName())));
//            if (receive != null && receive.getState().equals("未接收")) {
//                receive.setState("已接收");
//                receive.setReceiveTime(LocalDateTime.now());
//                informReceiveRepository.updateByPrimaryKey(receive);
//                //未读数减一
//                inform.setUnread(String.valueOf(Integer.valueOf(inform.getUnread()) - 1));
//                informRepository.updateByPrimaryKey(inform);
//                log.info("用户：" + user.getUserName() + "接收到主题为'" +  receive.getTitle() + "'的通知");
//            }
//            vo.setContent(inform.getContent());
//        }
        if ("Law".equals(inform.getType())) {
            //附件列表
            List<PicVO> attachmentList = new ArrayList<>();
            //附件
            String attachment = inform.getAttachment();
            if (StringUtils.isNotEmpty(attachment)) {
                String[] files = attachment.split(",");
                for (String file : files) {
                    PicVO picVO = new PicVO();
                    picVO.setPath(file);
                    attachmentList.add(picVO);
                }
                //获取content
//                String f = files[0];
//                vo.setContent(inform.getTitle() + f.substring(f.lastIndexOf(".")));
            }
            vo.setAttachmentList(attachmentList);
        }
        BeanUtils.copyProperties(inform, vo);
        vo.setContent(inform.getContent());
        vo.setInformCode(inform.getInformCode());
        vo.setTitle(inform.getTitle());
        vo.setTime(inform.getTime());
        List<PicVO> vos = new ArrayList<>();
        //图片
        String picture = inform.getPicture();
        if (StringUtils.isNotEmpty(picture)) {
            String[] files = picture.split(",");
            for (String file : files) {
                PicVO picVO = new PicVO();
                picVO.setPath(file);
                vos.add(picVO);
            }
        }
        vo.setPicList(vos);
        return new Return(vo);
    }

    @Override
    public Return deleteInform(String informCode) {
        Inform inform = informRepository.findByPrimaryKey(informCode);
        inform.setIsDeleted(1);
        informRepository.updateByPrimaryKey(inform);
        return new Return(Return.SUCCESS, "操作成功");
    }

    @Override
    public Return editInform(Integer type, Inform inform) {
        if (type == 0) {
            inform.setType("Inform");
        } else {
            inform.setType("Law");
        }
        inform.setIsDeleted(0);
        inform.setTime(LocalDateTime.now());
        //生成图片和附件信息
        FileGenerate.generate(inform.getPicture(), inform.getUserName());
        FileGenerate.generate(inform.getAttachment(), inform.getUserName());
        //插入通知数据
        informRepository.updateByPrimaryKey(inform);
        return new Return(Return.SUCCESS, "操作成功");
    }
}
